package org.lzy.shop.adapter

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.activity.SearchResultActivity
import org.lzy.shop.response.ClassifyGroup
import org.lzy.shop.response.HomeClassifyTree
import org.lzy.shop.util.setUrl

class ClassifyGroupAdapter : BaseQuickAdapter<ClassifyGroup, QuickViewHolder>() {
    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
        return QuickViewHolder(R.layout.item_classify_group, parent)
    }

    override fun onBindViewHolder(
        holder: QuickViewHolder,
        position: Int,
        item: ClassifyGroup?
    ) {
        item?.let {
            holder.setText(R.id.tv_group_name, it.title)

            // 获取子分类RecyclerView
            val subRecyclerView = holder.getView<RecyclerView>(R.id.rv_sub_categories)

            // 设置子分类网格适配器
            val subAdapter = SubCategoryAdapter(it.categories)
            subRecyclerView.layoutManager = GridLayoutManager(context, 3)
            subRecyclerView.adapter = subAdapter
        }
    }

    /**
     * 子分类适配器
     */
    inner class SubCategoryAdapter(private val categories: List<HomeClassifyTree>) :
        RecyclerView.Adapter<SubCategoryViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubCategoryViewHolder {
            return SubCategoryViewHolder(QuickViewHolder(R.layout.item_classify_two, parent))
        }

        override fun onBindViewHolder(holder: SubCategoryViewHolder, position: Int) {
            val category = categories[position]
            holder.quickViewHolder.setText(R.id.tv_name, category.name)
            setUrl(category.pic, holder.quickViewHolder.getView(R.id.item_classify_right_icon))
            val params = holder.itemView.layoutParams as GridLayoutManager.LayoutParams
            params.setMargins(10, 10, 10, 10)
            // 设置点击事件
            holder.quickViewHolder.itemView.setOnClickListener {
                val list = ArrayList<Int?>()
                list.add(category.id.toInt())
                val bundle = Bundle()
                bundle.putIntegerArrayList(Constant.TYPE_ID, list)
                // 使用context启动Activity
                val intent = Intent(context, SearchResultActivity::class.java)
                intent.putExtras(bundle)
                context.startActivity(intent)
            }
        }

        override fun getItemCount(): Int {
            return categories.size
        }
    }

    class SubCategoryViewHolder(val quickViewHolder: QuickViewHolder) : RecyclerView.ViewHolder(quickViewHolder.itemView)


}